package com.game.service.app;


import com.game.service.define.RoomConfig;
import com.game.service.socket.FileUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import static com.game.service.app.Utils.LogDate;
import static com.game.service.define.RoomConfig.LOG_NAME_ERROR;


public class Score {
    public static final String API_GET_COIN = String.format("https://%s/game/userBalanceV2", RoomConfig.URL);//获取玩家分数
    public static final String API_GET_CONFIG = String.format("https://%s/game/guessSizeConfigV2", RoomConfig.URL);//获取配置
    public static final String API_POST_FEE_ORDER = String.format("https://%s/game/guessSizeOrderV2", RoomConfig.URL);//门票订单(消耗)
    public static final String API_POST_PRIZE_ORDER = String.format("https://%s/game/guessSizeSettleSinglePlayer", RoomConfig.URL);//结算(增加)
    //上传在线用户
    public static final String API_POST_ONLINE_USER_REPORT = String.format("https://%s/game/onlineUserReport", RoomConfig.URL);//实时在线用户
    //比赛配置
    public static final String API_POST_MATCH_RANKING_EVENT = String.format("https://%s/game/rankingEvent", RoomConfig.URL);
    //新增比赛积分排行榜
    public static final String API_POST_MATCH_RANKING = String.format("https://%s/game/matchRanking", RoomConfig.URL);
    //新增比赛记录
    public static final String API_POST_MATCH_PLAYING = String.format("https://%s/game/matchPlaying", RoomConfig.URL);


    /**
     * GET请求.
     *
     * @param url 请求地址
     * @return 响应数据
     */
    public static String doGet(String url) {
        HttpURLConnection urlConnection = null;
        try {
            // 新建URL对象
            URL urlObject = new URL(url);
            // 打开URL连接
            urlConnection = (HttpURLConnection) urlObject.openConnection();
            // 设置请求方法
            urlConnection.setRequestMethod("GET");
            // 设置请求头内容类型和字符集类型
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 不使用缓存
            urlConnection.setUseCaches(false);
            // 设置连接超时时间，单位：毫秒
            urlConnection.setConnectTimeout(3000);
            // 设置读取数据超时时间，单位：毫秒
            urlConnection.setReadTimeout(3000);

            // 获取响应
            return inputStreamProcess(urlConnection);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取响应参数.
     *
     * @param urlConnection Http连接对象
     * @param params        请求参数
     * @return 响应数据
     */
    private static String responseProcess(URLConnection urlConnection, String params) {
        try (PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream())) {
            // 发送请求参数
            printWriter.print(params);
            // 刷新输出流
            printWriter.flush();
            return inputStreamProcess(urlConnection);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取响应数据.
     *
     * @param urlConnection Http连接对象
     * @return 响应数据
     */
    private static String inputStreamProcess(URLConnection urlConnection) {
        try (InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    /**
     * @param httpUrl 请求的url
     * @param json    json格式
     */
    public static String doPostForm(String httpUrl, String json) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(3000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(5000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            //设置加密方式,发送给总服务器
            connection.setRequestProperty("Encryption-Type", "RSA");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            //connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的(form表单形式的参数实质也是key,value值的拼接，类似于get请求参数的拼接)

            os.write(json.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));

                StringBuilder sbf = new StringBuilder();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
           // e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    String error = "doPostForm" + e + "\n" + Arrays.toString(e.getStackTrace());
                    FileUtils.writeTxtToFile(error, LogDate(), LOG_NAME_ERROR);

                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    String error = "doPostForm" + e + "\n" + Arrays.toString(e.getStackTrace());
                    FileUtils.writeTxtToFile(error, LogDate(), LOG_NAME_ERROR);
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    String error = "doPostForm" + e + "\n" + Arrays.toString(e.getStackTrace());
                    FileUtils.writeTxtToFile(error, LogDate(), LOG_NAME_ERROR);
                }
            }
            // 断开与远程地址url的连接
            if (connection != null) {
                connection.disconnect();
            }
        }
        return result;
    }


}
